unit fSelectObj;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ActnList, FIBQuery, pFIBQuery, uDM, ComCtrls;

type
  TfrmSelectObj = class(TForm)
    btnSelect: TButton;
    ActionList1: TActionList;
    actSelect: TAction;
    qryObj: TpFIBQuery;
    btnAdd: TButton;
    lvList: TListView;
    procedure actSelectUpdate(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure btnAddClick(Sender: TObject);
    procedure actSelectExecute(Sender: TObject);
  private
    { Private declarations }
    FIsJur: Boolean;
    DefID: Integer;
    procedure FillCard(IsJur: Boolean);
  public
    { Public declarations }
    class function Select(IsJur: Boolean; Default: Integer = -1): Integer;
  end;

implementation

Uses Obj_Consts, fAddObj;

{$R *.dfm}

procedure TfrmSelectObj.actSelectExecute(Sender: TObject);
begin
  if lvList.ItemIndex <> -1 then
    ModalResult := mrOk;
end;

procedure TfrmSelectObj.actSelectUpdate(Sender: TObject);
begin
  actSelect.Enabled := lvList.ItemIndex <> -1;
end;

procedure TfrmSelectObj.FillCard(IsJur: Boolean);
var
  ID, I: Integer;
  strs: TStringList;
begin
  strs := nil;
  lvList.Items.BeginUpdate;
  try
    lvList.Clear;
    qryObj.SQL.Text := 'Select * from Objects where ISJUR = :i';
    qryObj.ParamByName('i').AsInteger := FBool(IsJur);
    qryObj.ExecQuery;
    strs := TStringList.Create;
    while not qryObj.Eof do
    begin
      ID := qryObj.FieldByName('ID').AsInteger;
      strs.AddObject(TObj.GetName(ID), TObject(ID));
      qryObj.Next;
    end;
    strs.Sort;
    for I := 0 to strs.Count - 1 do
      lvList.AddItem(strs[I], strs.Objects[I]);
  finally
    lvList.Items.EndUpdate;
    strs.Free;
    qryObj.Close;
  end;
end;

class function TfrmSelectObj.Select(IsJur: Boolean; Default: Integer = -1): Integer;
var
  frm: TfrmSelectObj;
begin
  Result := 0;
  frm := TfrmSelectObj.Create(nil);
  with frm do
  try
    FIsJur := IsJur;
    FillCard(IsJur);
    DefID := Default;
    if (ShowModal = mrOk) and (lvList.ItemIndex <> -1) then
      Result := Integer(lvList.Items[lvList.ItemIndex].Data);
  finally
    frm.Free;
  end;
end;

procedure TfrmSelectObj.FormShow(Sender: TObject);
var
  I: Integer;
begin
  if DefID <> -1 then begin
    for i := 0 to lvList.Items.Count - 1 do
      if Integer(lvList.Items[i].Data) = DefID then begin
        lvList.ItemIndex := i;
        Exit;
      end;
  end;
end;

procedure TfrmSelectObj.btnAddClick(Sender: TObject);
var
  ID: Cardinal;
begin
  ID := TfrmAddObj.AddOrSelectObj(FIsJur);
  if ID <> 0 then
    lvList.AddItem(TObj.GetName(ID), TObject(ID));
end;

end.
